package com.itheima.mall.service.ums;

import com.itheima.mall.api.ums.UmsMenuServiceApi;
import com.itheima.mall.pojo.ums.UmsMenu;
import com.itheima.mall.vo.R;
import com.itheima.mall.vo.UmsMenuVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UmsMenuService {

    @DubboReference
    UmsMenuServiceApi umsMenuServiceApi;

    public R UmsMenuCreate(UmsMenu umsMenu) {
        return umsMenuServiceApi.UmsMenuCreate(umsMenu);
    }

    public R UmsMenuDelete(Long id) {
        return umsMenuServiceApi.UmsMenuDelete(id);
    }

    public R UmsMenuList(Long parentId, Integer pageNum, Integer pageSize) {
        return umsMenuServiceApi.UmsMenuList(parentId,pageNum,pageSize);
    }

    public R UmsMenuTreeList() {
        List<UmsMenu> umsMenuList = umsMenuServiceApi.UmsMenuTreeList();

        List<UmsMenuVo> umsMenuVoList = new ArrayList<>();

        for (UmsMenu umsMenu : umsMenuList) {
            if (umsMenu.getParentId()==0){
                UmsMenuVo umsMenuVoTemp = new UmsMenuVo();
                BeanUtils.copyProperties(umsMenu,umsMenuVoTemp);
                umsMenuVoList.add(umsMenuVoTemp);
            }
        }

        List result = findChildren(umsMenuList, umsMenuVoList);

        return R.succeed(result,"查找成功");
    }

    /**
     * 递归查找子菜单
     * @param umsMenuList
     * @param umsMenuVoList
     * @return
     */
    private List findChildren(List<UmsMenu> umsMenuList, List<UmsMenuVo> umsMenuVoList){

        //遍历需要查找的父级菜单
        for (UmsMenuVo umsMenuVo : umsMenuVoList) {

            List<UmsMenuVo> umsMenuVoListTemp = new ArrayList<>();
            //循环所有菜单
            for (UmsMenu umsMenu : umsMenuList) {
                //将所有菜单
                if (umsMenu.getParentId().equals(umsMenuVo.getId())){
                    UmsMenuVo umsMenuVoTemp = new UmsMenuVo();
                    BeanUtils.copyProperties(umsMenu,umsMenuVoTemp);
                    umsMenuVoListTemp.add(umsMenuVoTemp);
                }
            }
            //递归调用查询子菜单的子菜单
            findChildren(umsMenuList,umsMenuVoListTemp);
            //将整理完成的子菜单存入Children
            umsMenuVo.setChildren(umsMenuVoListTemp);
        }
        return umsMenuVoList;
    }

    public R UmsMenuUpdate(Long id, UmsMenu umsMenu) {
        return umsMenuServiceApi.UmsMenuUpdate(id,umsMenu);
    }

    public R UmsMenuUpdateHidden(Long id, Integer hidden) {
        return umsMenuServiceApi.UmsMenuUpdateHidden(id,hidden);
    }

    public R UmsMenuFindById(Long id) {
        return umsMenuServiceApi.UmsMenuFindById(id);
    }
}
